package com.example.demo.packageTest;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.nio.charset.Charset;
import java.util.UUID;

public class PackageServerHandler extends SimpleChannelInboundHandler<MessageProtocol> {

    protected void channelRead0(ChannelHandlerContext ctx, MessageProtocol msg) throws Exception {

        int len = msg.getLen();
        byte[] content = msg.getContent();
        System.out.println("服务器接收到信息如下");
        System.out.println("长度=" + len);
        System.out.println("内容=" + new String(content, Charset.forName("utf-8")));

        //回复消息
        String responseContent = UUID.randomUUID().toString();
        int responseLen = responseContent.getBytes("utf-8").length;
        byte[] responseContent2 = responseContent.getBytes("utf-8");

        //构建一个协议包
        MessageProtocol protocol = new MessageProtocol();
        protocol.setLen(responseLen);
        protocol.setContent(responseContent2);
        ctx.writeAndFlush(protocol);
    }
}
